package com.sfac.day03.modules.account.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sfac.day03.modules.account.dao.ResourceDao;
import com.sfac.day03.modules.account.dao.RoleResourceDao;
import com.sfac.day03.modules.account.entity.Resource;
import com.sfac.day03.modules.account.entity.RoleResource;
import com.sfac.day03.modules.account.service.ResourceService;
import com.sfac.day03.modules.common.entity.ResultEntity;
import com.sfac.day03.modules.common.entity.SearchBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class ResourceServiceImpl implements ResourceService {
    @Autowired
    private ResourceDao resourceDao;
    @Autowired
    private RoleResourceDao roleResourceDao;
    @Override
    public ResultEntity<Resource> insertResource(Resource resource) {
        resource.setCreateDate(LocalDateTime.now());
        resourceDao.insertResource(resource);
        if (resource.getRoles()!=null){
            resource.getRoles().stream().forEach(item ->{roleResourceDao.insertRoleResource(new RoleResource(item.getId(),resource.getId()));});
        }
        return new ResultEntity<Resource>(ResultEntity.ResultStatus.SUCCESS.code,"insert sucess",resource);
    }

    @Override
    public ResultEntity<Resource> updateResource(Resource resource) {
        resource.setCreateDate(LocalDateTime.now());
        resourceDao.updateResource(resource);
        if (resource.getRoles()!=null){
            resource.getRoles().stream().forEach(item ->{roleResourceDao.insertRoleResource(new RoleResource(item.getId(),resource.getId()));});
        }
        return new ResultEntity<Resource>(ResultEntity.ResultStatus.SUCCESS.code,"update sucess",resource);
    }

    @Override
    public ResultEntity<Object> deleteResourceById(int id) {
        resourceDao.deleteResourceById(id);
        roleResourceDao.deleteRoleResourceByRoleId(id);
        return new ResultEntity<Object>(ResultEntity.ResultStatus.SUCCESS.code,"delete sucess");
    }

    @Override
    public Resource getResourceById(int id) {
       return resourceDao.getResourceById(id);

    }

    @Override
    public List<Resource> getResourcesByRoleId(int roleId) {
       return resourceDao.getResourcesByRoleId(roleId);
    }

    @Override
    public PageInfo<Resource> getResourcesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getPageNumber(),searchBean.getPageSize());
        return new PageInfo<Resource>(Optional.ofNullable(resourceDao.getResourcesBySearchBean(searchBean))
        .orElse(Collections.emptyList()));

    }
}
